#include <QApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QDebug>
#include <QNetworkRequest>
#include <QJsonParseError>
#include <QJsonDocument>
#include <QByteArray>

void finished(QNetworkReply* reply);

int main(int argc, char** argv)
{
    QApplication app(argc, argv);

    QMap<QString, QString> citys;
    citys["beijin"] = "101010100";
    citys["shanghai"] = "101020100";
    citys["suzhou"] = "101190401";

    QNetworkAccessManager manager;
    QObject::connect(&manager, &QNetworkAccessManager::finished,
                     &::finished);
    // 数据来自中国天气网
    QString url = QString("http://www.weather.com.cn/data/cityinfo/%1.html")
                         .arg(citys["shanghai"]);
    manager.get(QNetworkRequest(QUrl(url)));

    return app.exec();
}

void finished(QNetworkReply* reply)
{
    if (reply != NULL){
        QByteArray json = reply->readAll();
        //qDebug() << json;
        QJsonParseError error;
        QJsonDocument jsonDoument = QJsonDocument::fromJson(json, &error);
        if (error.error == QJsonParseError::NoError){
            if (jsonDoument.isObject()){
                QVariantMap result = jsonDoument.toVariant().toMap();
                QVariantMap info = result["weatherinfo"].toMap();
                qDebug() << "城市:" << info["city"].toString()
                         << "\n温度:" << info["temp1"].toString()
                         << "~" << info["temp2"].toString()
                         << "\n天气:" << info["weather"].toString()
                         << "\n更新时间:" << info["ptime"].toString();
            }
        }else{
            qDebug() << "Error: " << error.errorString();
            exit (1);
        }
    }
}
